﻿using System.Diagnostics;

using Microsoft.Extensions.ObjectPool;

namespace zijian666.Data;

internal static class ObjectPoolHelper
{
    public readonly struct Retrunable<T>(ObjectPool<T> pool, T value) : IDisposable
        where T : class
    {
        private readonly ObjectPool<T> _pool = pool ?? throw new ArgumentNullException(nameof(pool));
        private readonly T _value = value;

        public void Dispose() => _pool.Return(_value);
    }


    private static ObjectPool<StringBuilder> _stringBuilderPool = ObjectPool.Create(new StringBuilderPooledObjectPolicy());

    public static Retrunable<StringBuilder> GetStringBuilder(out StringBuilder stringBuilder)
    {
        stringBuilder = _stringBuilderPool.Get();
        return new Retrunable<StringBuilder>(_stringBuilderPool, stringBuilder);
    }

    private static ObjectPool<DbParameterFormatProvider> _pfpPool = ObjectPool.Create(new PooledObjectPolicy<DbParameterFormatProvider>());

    public static Retrunable<DbParameterFormatProvider> GetDbParameterFormatProvider(out DbParameterFormatProvider provider)
    {
        provider = _pfpPool.Get();
        return new Retrunable<DbParameterFormatProvider>(_pfpPool, provider);
    }

    private static ObjectPool<Stopwatch> _stopwatchPool = ObjectPool.Create(new PooledObjectPolicy<Stopwatch>(x => x.Reset()));

    public static Retrunable<Stopwatch> GetStopwatch(out Stopwatch stopwatch)
    {
        stopwatch = _stopwatchPool.Get();
        return new Retrunable<Stopwatch>(_stopwatchPool, stopwatch);
    }
}